//
//  MNDInvestmentDetailViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/13.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDInvestmentDetailViewController.h"
#import "MNDInvestmentDetailCell.h"
#import "MNDTransferDetailCell.h"
//#import "MNDInvestmentDetailView.h"
#import "MNDInvestmentDetailHeaderView.h"
#import "MNDInvestmentDetailModel.h"
#import "ArabicTranslation.h"
#import "MNDInvestmentSectionModel.h"
#import "MNDConfirmTransferViewController.h"
#import "MNDWebViewController.h"
#import "UIView+JKVisuals.h"
#import "NSDate+JKExtension.h"
#import "NSDate+JKFormatter.h"

@interface MNDInvestmentDetailViewController () <UITableViewDataSource, UITableViewDelegate>

/*! 标题: 待收总额或回款总额*/
@property (weak, nonatomic) IBOutlet UILabel *returnTotalMoneyTitleLabel;
/*! 待收总额或回款总额 */
@property (weak, nonatomic) IBOutlet UILabel *returnTotalMoneyLabel;

/*! 标题：待收本金或者回款本金 */
@property (weak, nonatomic) IBOutlet UILabel *returnPrincipalTitleLabel;
/*! 待收本金或者回款本金 */
@property (weak, nonatomic) IBOutlet UILabel *returnPrincipalLabel;

/*! 投资本金 */
@property (weak, nonatomic) IBOutlet UILabel *principalLabel;
/*! 待收收益或已收收益 */
@property (weak, nonatomic) IBOutlet UILabel *profitLabel;
/*! 标题: 待收收益或已收收益 */
@property (weak, nonatomic) IBOutlet UILabel *profitTitleLabel;

@property (weak, nonatomic) IBOutlet UILabel *borrowTitleLabel;

/*! 帮助按钮 */
@property (weak, nonatomic) IBOutlet UIButton *helpButton;
/*! 年化利率 */
@property (weak, nonatomic) IBOutlet UILabel *annualRateLabel;
/*! 奖励利率 */
@property (weak, nonatomic) IBOutlet UILabel *rewardProfitRateLabel;
/*! 有奖励图标 */
@property (weak, nonatomic) IBOutlet UIImageView *rewardImage;
/*! 投资期限 */
@property (weak, nonatomic) IBOutlet UILabel *deadlineLabel;
/*! 投资日期 */
@property (weak, nonatomic) IBOutlet UILabel *investDateLabel;
/*! 到期日期或结清日期 */
@property (weak, nonatomic) IBOutlet UILabel *endDateLabel;
/*! 标题: 到期日期或结清日期 */
@property (weak, nonatomic) IBOutlet UILabel *endDateTitleLabel;

/*! 已结清或者提前还款等的印章 */
@property (weak, nonatomic) IBOutlet UIImageView *returnStatusTagImage;


@property (strong, nonatomic) MNDInvestmentDetailModel *detailModel;

@property (strong, nonatomic) NSMutableArray *returnArray;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;

@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;
@property (weak, nonatomic) IBOutlet UIView *helpView;
@property (weak, nonatomic) IBOutlet UIView *blankFooterView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLeadingConstrainnt;
@property (weak, nonatomic) IBOutlet UILabel *transferTag;

//@property (strong, nonatomic) MNDInvestmentDetailHeaderView *detailheaderView;

/**
 展期协按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *protocolButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *statusImgTrailingMargin;

@end

@implementation MNDInvestmentDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200.0;
    [self.noticeLabel jk_cornerRadius:3 strokeSize:1 color:kColorGray];
    self.noticeLabel.layer.masksToBounds = YES;
    self.helpView.alpha = 0.0;
    
    [self.blankFooterView setHidden:YES];
    
    if (self.shouldCustomBack) {
        [self customBackBarButton];
    }
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"查看协议"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(readProtocolAction:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)readProtocolAction: (id)sender {
    if (!self.detailModel ) {
        return;
    }
    
    WeakSelf(self);
    
    if (!self.detailModel.tender.transfer_id) { //投资协议
        [NetworkProgressHUD showHud];
        NSDictionary *params = [MNDSign signedParamWithDict:@{@"tender_id": self.tenderId, @"operation": @"4"}];
        [APIManager sendRequestWithPath:API_TENDER_PROTOCOL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            
            if (responseModel.status == ResponseSuccess) {
                [NetworkProgressHUD hideHud];
                MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
                webVC.webViewUrl = responseModel.data;
                webVC.naviBarHidden = NO;
                webVC.loadType = LoadTypeLink;
                webVC.title = @"借款协议";
                UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
                [weakself presentViewController:naviVC animated:YES completion:^{
                    
                }];
            } else {
                NSDictionary *dict = responseModel.msg;
                if (dict && dict.count > 0) {
                    [NetworkProgressHUD showHudMsg:dict[@"error"]];
                } else {
                    [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
                }
            }
            
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD showHudNetworkError:error];
        }];
    } else { //债转协议
        [NetworkProgressHUD showHud];
        NSDictionary *params = [MNDSign signedParamWithDict:@{@"transfer_id": self.detailModel.tender.transfer_id, @"operation": @"4"}];
        [APIManager sendRequestWithPath:API_TRANSFER_PROTOCOL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            
            if (responseModel.status == ResponseSuccess) {
                [NetworkProgressHUD hideHud];
                MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
                webVC.webViewUrl = responseModel.data;
                webVC.naviBarHidden = NO;
                webVC.loadType = LoadTypeLink;
                webVC.title = @"转让协议";
                UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
                [weakself presentViewController:naviVC animated:YES completion:^{
                    
                }];
            } else {
                NSDictionary *dict = responseModel.msg;
                if (dict && dict.count > 0) {
                    [NetworkProgressHUD showHudMsg:dict[@"error"]];
                } else {
                    [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
                }
            }
            
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD showHudNetworkError:error];
        }];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadInvestmentDetail];
}

- (void)loadInvestmentDetail {
    
    [NetworkProgressHUD showHud];
    WeakSelf(self);
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"tender_id": self.tenderId}];
    [APIManager sendRequestWithPath:API_USER_TENDER_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakself.detailModel = [MNDInvestmentDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakself configInvestmentDetails];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configInvestmentDetails {
    NSInteger tenderStatus = self.detailModel.tender.tender_status.integerValue;
    
    if (self.detailModel.tender.hide_contract.integerValue == 1) {
        [self initialBarbuttonItems];
    }

    if (tenderStatus == 1 || tenderStatus == 2 || self.detailModel.tender.borrow_extension_num.integerValue) {
        [self.helpButton setHidden:YES];
        self.returnTotalMoneyTitleLabel.text = @"回款总额(元)";
        self.profitTitleLabel.text = @"已获收益(元)";
        
        self.returnTotalMoneyLabel.text = self.detailModel.tender.return_actual_amount;
        self.profitLabel.text = self.detailModel.tender.return_actual_already_income;
        
        self.endDateTitleLabel.text = @"结清日期";
        self.endDateLabel.text = self.detailModel.tender.return_actual_end_date;
        
        self.returnPrincipalTitleLabel.text = @"回款本金(元)";
        self.returnPrincipalLabel.text = self.detailModel.tender.return_actual_principal;
//        NSString *imageName = @"investment_record_completed";
        
//        if (self.detailModel.tender.tender_status.integerValue == 2) {
//            imageName = @"investment_record_trasfered";
//        }
//        if (self.detailModel.tender.borrow_extension_num.integerValue > 0) {
//            imageName = @"investment_record_overdue";
//        }
//        [self.returnStatusTagImage setHidden:NO];
//        self.returnStatusTagImage.image = [UIImage imageNamed:imageName];
    } else {
        //收益中
        self.returnTotalMoneyTitleLabel.text = @"待收总额(元)";
        self.profitTitleLabel.text = @"待收收益(元)";
        
        self.returnTotalMoneyLabel.text = self.detailModel.tender.return_amount;
        self.profitLabel.text = self.detailModel.tender.return_already_income;
        [self.helpButton setHidden:YES];
        self.endDateTitleLabel.text = @"到期日期";
        self.endDateLabel.text = self.detailModel.tender.return_end_date;
        
        self.returnPrincipalTitleLabel.text = @"待收本金(元)";
        self.returnPrincipalLabel.text = self.detailModel.tender.return_principal;
    }
    
    if (self.detailModel.tender.tender_status_icon.integerValue == 1) {//提前还款
        [self.returnStatusTagImage setHidden:NO];
        [self.returnStatusTagImage setImage:[UIImage imageNamed:@"investment_record_ahead"]];
    }else if (self.detailModel.tender.tender_status_icon.integerValue == 2) {//已转让
        [self.returnStatusTagImage setHidden:NO];
        [self.returnStatusTagImage setImage:[UIImage imageNamed:@"investment_record_trasfered"]];
    }else if (self.detailModel.tender.tender_status_icon.integerValue == 3) {//已结清
        [self.returnStatusTagImage setHidden:NO];
        [self.returnStatusTagImage setImage:[UIImage imageNamed:@"investment_record_completed"]];
        
    }else if (self.detailModel.tender.tender_status_icon.integerValue == 4) {//已展期
        [self.returnStatusTagImage setHidden:NO];
        self.statusImgTrailingMargin.constant = 40;
        [self.returnStatusTagImage setImage:[UIImage imageNamed:@"investment_record_overdue"]];
        [self.protocolButton setHidden:NO];
        
        [self.protocolButton addTarget:self action:@selector(extensionAgreementAction:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [self.returnStatusTagImage setHidden:YES];
    }
    self.borrowTitleLabel.text = self.detailModel.detial_title;
    self.principalLabel.text = self.detailModel.tender.tender_money;
    self.annualRateLabel.text = [NSString stringWithFormat:@"%@%%", self.detailModel.borrow_year_apr];
    if (self.detailModel.sum_apr.doubleValue > 0) {
        self.rewardProfitRateLabel.text = [NSString stringWithFormat:@"+%.02f%%", self.detailModel.sum_apr.doubleValue * 100];
        [self.rewardProfitRateLabel setHidden:NO];
        [self.rewardImage setHidden:NO];
    } else {
        self.rewardProfitRateLabel.text = @"";
        [self.rewardProfitRateLabel setHidden:YES];
        [self.rewardImage setHidden:YES];
    }
    self.deadlineLabel.text = [NSString stringWithFormat:@"%@个月", self.detailModel.borrow_deadline];
    self.investDateLabel.text = self.detailModel.tender_add_time;
    
    [self.returnArray removeAllObjects];
    
    for (NSInteger i = 0; i < self.detailModel.list.count; i++) {
        MNDInvestmentSectionModel *sectionModel = [MNDInvestmentSectionModel new];

        sectionModel.isSectionExpand = NO;
        sectionModel.returnModel = self.detailModel.list[i];
        [self.returnArray addObject:sectionModel];
    }
    
    [self.blankFooterView setHidden:self.returnArray.count];
    [self.tableView reloadData];
    
    CGSize titleSize = [self.detailModel.detial_title boundingRectWithSize:CGSizeMake(kScreenWidth - 30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size;
    if (titleSize.height > 18) {
        [self.tableView beginUpdates];
        [self.tableView.tableHeaderView setFrame:CGRectMake(0, 0, kScreenWidth, 330)];
        [self.tableView endUpdates];
    }
    
    //显示隐藏标题右边的债转标签
    if (self.detailModel.transfer_in) {
        [self.transferTag setHidden:NO];
        self.titleLeadingConstrainnt.constant = 5;
    } else {
        [self.transferTag setHidden:YES];
        self.titleLeadingConstrainnt.constant = -34;
    }
    
    //显示隐藏债转按钮
    if (!self.allowTransfer) {
        return;
    }
    if (self.detailModel.is_transfer.integerValue == 1) {
        self.bottomSpace.constant = 0.0;
    } else {
        self.bottomSpace.constant = -44.0;
    }
}

- (IBAction)helpAction:(id)sender {
    
    [UIView animateWithDuration:0.2 animations:^{
        if (self.noticeLabel.alpha == 0) {
            self.noticeLabel.alpha = 1.0;
            self.helpView.alpha = 1.0;
        } else {
            self.noticeLabel.alpha = 0.0;
            self.helpView.alpha = 0.0;
        }
    }];
}


- (void)customBackBarButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    [self.tabBarController setSelectedIndex:3];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//点击转让债权
- (IBAction)transferCreditorAction:(UIButton*)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TenderTransfer" bundle:nil];
    MNDConfirmTransferViewController *confirmTransferVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDConfirmTransferViewController"];
    confirmTransferVC.tenderId = self.tenderId;
    confirmTransferVC.yearApr = self.detailModel.borrow_year_apr;
//    confirmTransferVC.detailModel = self.detailModel;
    [self.navigationController pushViewController:confirmTransferVC animated:YES];
}


/**
 点击展期协议

 @param sender
 */
- (void)extensionAgreementAction:(UIButton *)sender {
    [NetworkProgressHUD showHud];
    WeakSelf(self);
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"tender_id": self.tenderId}];
    
    [APIManager sendRequestWithPath:API_EXTENSION_PROTOCOL_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        NSLog(@"response: %@", responseModel.data);
        if (responseModel.status == ResponseSuccess) {
            MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
            webVC.webViewUrl = responseModel.data;
            webVC.naviBarHidden = NO;
            webVC.loadType = LoadTypeLink;
            webVC.title = @"借款展期协议";
            UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
            [weakself presentViewController:naviVC animated:YES completion:^{
                
            }];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        NSLog(@"error: %@", error);
    }];
}

#pragma mark - UITableView Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.returnArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MNDInvestmentSectionModel *model = self.returnArray[section];
    if (model.isSectionExpand) {
        return 1;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    MNDInvestmentDetailHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
        MNDInvestmentSectionModel *model = self.returnArray[section];
    if (!headerView) {
        headerView = [[MNDInvestmentDetailHeaderView alloc] initWithReuseIdentifier:@"header"];
        
    }
    headerView.model = model;
    headerView.deadlineLabel.text = [NSString stringWithFormat:@"第%@期", [ArabicTranslation translationArabicNum:section + 1]];
    
    if (model.returnModel.status.integerValue == 1) {
        headerView.returnStatusLabel.textColor = kColorOrange;
    } else {
        headerView.returnStatusLabel.textColor = kColorGray;
    }
    headerView.returnStatusLabel.text = model.returnModel.status_name;
    headerView.returnMoneyLabel.text = model.returnModel.sum_amount;
    
    WeakSelf(self);
    headerView.headerClickedBack = ^(BOOL expand){
        [weakself updateTableViewSection:section];
       
    };
    
    return headerView;
}

- (void)updateTableViewSection:(NSInteger)section {
//    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
//    [self.tableView endUpdates];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *const cellIdentifier = @"investmentCell";
    MNDInvestmentDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    MNDInvestmentSectionModel *sectionModel = self.returnArray[indexPath.section];
    MNDInvestmentDetailReturnModel *model = sectionModel.returnModel;
    [cell configCellWithModel:model];
    
    return cell;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (MNDInvestmentDetailModel *)detailModel {
    if (!_detailModel) {
        _detailModel = [[MNDInvestmentDetailModel alloc] init];
    }
    
    return _detailModel;
}

- (NSMutableArray *)returnArray {
    if (!_returnArray) {
        _returnArray = [NSMutableArray array];
    }
    
    return _returnArray;
}

@end
